<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';

if ($argc != 2) {
        echo "\nImport shipping records into Yubico database:\n";
        echo "% php import_buyers shipping_record.csv\n";
        exit;
}

$fname = $argv[1];
if (! ($in = fopen($fname, "r"))) {
     echo 'Cannot open file '.$fname."\n";
     exit(1);
}

// If run from the web
//header("content-type: text/plain");
//$fname = '/yubico/OrderRecords_20080929.csv';
//echo "\nImport shipping records into Yubico database:\n";
//echo "% php import_buyers shipping_record.csv\n";

if (! ($in = fopen($fname, "r"))) {
     echo 'Cannot open file '.$fname."\n";
     exit(1);
}

//$mesg = fread($in, filesize($argv[1]));
$clientsAdded = $rowN = $buyersAdded = $keysIssued = $skipped = 0;
$skip = array();
while (($data = fgetcsv($in, 1000, ",")) !== FALSE) {
	$rowN++;
    if (($n = count($data)) < 3) {
        continue;
    }
    
    $orderDate = $data[3];
    $name = trim($data[1]).' '.trim($data[2]);
    $offset = 17;
    $addr = (isset($data[$offset]) ? trim($data[$offset]) : '');
    $email = (isset($data[$offset+2]) ? strtolower(trim($data[$offset+2])) : '');
    $keys = (isset($data[$offset+3]) ? strtolower(trim($data[$offset+3])) : '');
    $qty = (isset($data[$offset+4]) ? $data[$offset+4] : '');
    if (trim($qty) == '') {
    	$qty = 1;
    }
    
    echo '- name: '.$name."\n";
    echo '- orderDate: '.$orderDate."\n";
    echo '- addr: '.$addr."\n";
    echo '- email: '.$email."\n";
    echo '- qty: '.$qty."\n";
    echo '- keys: '.$keys."\n";
    
    if (strpos($email, '@') === false && strlen($keys) < 30) { // Skip
    	$skipped++;	$skip[$rowN] = $data;
    	echo 'invalid row: '.$rowN."\n";
    	continue;
    }
    
    ///////////////////////////////////////////////////////
    // For each key, 2 OTPs are required:
    // 1st round finds/creates its client
    // 2nd OTP round assigns the key to the client
    
	$otps = explode("\n", $keys);
	$client = 0;
	foreach ($otps as $otp) {
		$a = explode(' ', $otp);
		foreach ($a as $otp1) {
			$otp1 = trim($otp1);
			if (strlen($otp1) < 12) { continue ; }
			echo 'OTP: ['.$otp1."]\n";
			$devid = substr($otp1, 0, 12);
			$ki = getKeyInfo($devid);
			if (!isset($ki['keyid'])) {
				echo $devid.' non-exists Yubikey in DB in row '.$rowN."\n";
				$skipped++;	$skip[$rowN] = $data;
    			continue;
			}
			
			$keyid = $ki['keyid'];
			echo '> Client = '.$client.', keyId = '.$keyid."\n";
			//print_r($ki);
			if ($client > 1) {
				if ($ki['client'] <= 1) {	// A new key
					echo "! This is a new key, assign to client-".$client."\n";
					if (updClientOfKey($keyid, $client)) {
						$keysIssued++;
						echo 'Assign key '.$devid.' to client '.$client."\n";
					} else {
						echo 'Failed to assign key to client '.$client."\n";
					}
				} else if ($client != $ki['client']) { // Key ownership conflict
					echo $devid.' is owned by client '.$ki['client'].
						' in row '.$rowN."\n";
					continue;
				} else {
					echo 'Key '.$devid.' already assigned to client '.$client."\n";					
				}
			}
			
			if (($client=$ki['client']) <= 1) { // New key w/o a client	
				if (($client=getClientByEmail($email)) <= 1) { // Srch client by email
				  // No client owner of the key, add a new client
				  if (($client = addClient($email, genAPIKey(), 3, 
					'Imported from shipping record on '.$orderDate)) > 1) {
				  		$clientsAdded++;
					}
				}
			}
			
			echo '>> Client = '.$client."\n";
			
			if ($client <= 1) { // Failed to find or add a new client
				echo 'Failed addClient for buyer '.$email."\n";
				$skipped++;	$skip[$rowN] = $data;
    			break;
			} else {							
				if (getBuyerByClient($client) <= 0) {
					addBuyer($client, $name, $addr, $email, $qty);
					$buyersAdded++;
				}
			}
		} // End of foreach OTP
	} // End of foreach OTP str
    
    echo "\n\n";

} // End of while each CSV line

fclose($in);

echo $keysIssued." Yubikeys issued\n";
echo $clientsAdded." new clients added\n";
echo $buyersAdded." new buyers added\n";
echo $skipped." rows skipped\n";
if ($skipped > 0) {
	echo "Skipped rows: ";
   	//print_r($skip);
	foreach (array_keys($skip) as $rowNum) {
  		echo $rowNum.', ';
		//  $v = $skip[$rowNum];
		//  print_r($v);
		//  echo '\n';
	}
}

function getBuyerByClient($client) {
	$stmt = 'SELECT id FROM buyers WHERE client_id='.$client;
	if ($r = query($stmt)) {
		if (($row = mysql_fetch_assoc($r))) {
			mysql_free_result($r);		
			return $row['id'];
		}
	}
	return -1;
}

function addBuyer($client, $name, $addr, $email, $qty) {
	$stmt = 'INSERT INTO buyers (name,email,addr,qty,client_id,created) VALUES ('.
		mysql_quote(truncate($name,45)).','.
		mysql_quote(truncate($email,100)).','.
		mysql_quote(truncate($addr,200)).','.
		$qty.','.
		$client.','.
		'NOW())';
	if (query($stmt)) {
		return mysql_insert_id();	
	}
	return -1;
} // End addBuyer
?>
